﻿using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.Net;
using System.Net.Sockets;
using LJLNet;
using LJLCommon.Package;
using LJLCommon.Helper;
using System.Text;

public class ReceiveThread : BaseThread
{
    private SocketTCPPeer mSocketTCPPeer;

    public ReceiveThread(SocketTCPPeer socketTCPPeer)
    {
        mSocketTCPPeer = socketTCPPeer;
    }

    public override void Run()
    {
        if ( mThread != null && mSocketTCPPeer.mTcpSocket != null&& mSocketTCPPeer.mTcpSocket.Connected )
        {
            try
            {
                //socket接收消息  
                byte[] bt = new byte[1024];
                mSocketTCPPeer.mTcpSocket.Receive(bt);
                Debug.Log("接收响应");
                //对数据进行处理
                Package package = XMLHelper.Deserialze<Package>(ASCIIEncoding.UTF8.GetString(bt));
                Dictionary<byte, object> parameters = DictToPackageHelper.DeSerializa(package.parameters);
                //回调给主类处理           
                switch (package.type)
                {
                    case PackageType.Response:
                        mSocketTCPPeer.mMono.OnOperationResponse(parameters);
                        break;
                    case PackageType.Event:
                        mSocketTCPPeer.mMono.OnOperationEvent(parameters);
                        break;
                    default:
                        break;
                }
            }
            catch
            {
                //断开线程
                Stop();
                //断开连接
                Debug.Log("与服务器断开连接");
                mSocketTCPPeer.Disconnect();
            }
        }
    }
}
